package com.bfxy.rabbit.common.convert;

import com.google.common.base.Preconditions;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.MessageConversionException;
import org.springframework.amqp.support.converter.MessageConverter;

/**
 * @describte:装饰者模式（静态代理），加上一点点逻辑
 * @program:foodie-dev
 * @author:zhengdp
 * @create:2021-09-15 17:12:47
 **/
public class RabbitMessageConverter implements MessageConverter {

    private GenericMessageConverter delegate;

   // private final String defaultExprie = String.valueOf(24*60*60*1000);

    public RabbitMessageConverter(GenericMessageConverter genericMessageConverter){
        Preconditions.checkNotNull(genericMessageConverter);
        delegate = genericMessageConverter;
    }

    @Override
    public Message toMessage(Object object,
                             MessageProperties messageProperties)
            throws MessageConversionException {
        // 在发送消息时 进行一些额外的处理
        // 设置默认过期时间
        //messageProperties.setExpiration(defaultExprie);
        com.bfxy.rabbit.api.Message message = (com.bfxy.rabbit.api.Message) object;
        messageProperties.setDelay(message.getDelayMills());
        return this.delegate.toMessage(object,messageProperties);
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        com.bfxy.rabbit.api.Message msg = (com.bfxy.rabbit.api.Message) this.delegate.fromMessage(message);

        return msg;
    }
}
